<template>
    <div>
      <el-form ref="ruleForm" :model="form" :rules="rules" label-width="80px">
  
        <el-row>
          <el-col :span="6" :offset="1">
            <el-form-item label="商品类型">
              <el-select v-model="form.GTID" placeholder="请选择类型">
                <el-option v-for="item in types" :key="item.GTID" :label="item.Name" :value="item.GTID"></el-option>
  
              </el-select>
            </el-form-item>
            <el-form-item label="商品图片" prop="Images">
              <el-upload class="avatar-uploader" :action="baseapi + '/Files'" :show-file-list="false"
                :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                <img v-if="form.Images" :src="baseimg + form.Images" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            <el-form-item label="商品名称" prop="Name">
              <el-input v-model="form.Name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="Price">
              <el-input-number v-model="form.Price" :precision="2" :step="1" :min="0"></el-input-number>
            </el-form-item>
            <el-form-item label="商品单位" prop="Unit">
              <el-input v-model="form.Unit"></el-input>
            </el-form-item>
            <el-form-item label="商品描述" prop="Content">
              <el-input type="textarea" v-model="form.Content"></el-input>
            </el-form-item>
          </el-col>
  
          <el-col :span="14" :offset="2">
            <el-form-item label="属性">
              <el-switch v-model="form.Use_Property" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
            </el-form-item>
  
            <!-- 循环规格和规格的值 -->
            <el-form-item v-for="(item, index) in specs" :key="item.GSKID" :label="item.Name" v-show="form.Use_Property">
              <el-switch v-model="form.GoodPropertyKey[index].checked" @change="propchange" active-color="#13ce66"
                inactive-color="#ff4949"></el-switch>
              <el-checkbox-group v-show="form.GoodPropertyKey[index].checked"
                v-model="form.GoodPropertyKey[index].GoodPropertyValue">

                <el-checkbox v-for="v in item.Values" :name="item.Name" :key=v.GSVID :label="v.GSVID" :value="v.GSVID">
                  {{ v.Value }}
                </el-checkbox>
                
              </el-checkbox-group>
            </el-form-item>
  
  
          </el-col>
        </el-row>
      </el-form>
  
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="primary" @click="submitForm('ruleForm')">立即保存</el-button>
        <el-button @click="$emit('change', false)">取 消</el-button>
      </div>
  
  
    </div>
  </template>
  
  <script>
  import basepath from '../../plugins/base.js'
  export default {
    name: 'goodedit',
    data() {
      return {
        baseimg: '',
        baseapi: '',
  
        types: [],
        specs: [],
  
        form: {
          TID: 2,
          Images: '',
          Name: '冻顶乌龙',
          Content: '冻顶乌龙很好喝',
          Price: 18.00,
          Unit: '杯',
          Use_Property: true,
          Sort: 0,
          GoodPropertyKey: [
            {
              gskid: 1,  //规格 主键表  GoodSpecKey  id
              GoodPropertyValue: [],
              checked: true
            },
            {
              gskid: 2,
              GoodPropertyValue: [],
              checked: true
            },
            {
              gskid: 3,
              GoodPropertyValue: [],
              checked: true
            }
          ]
        }
  
        ,//表单验证规则
        rules: {
          Name: [
            { required: true, message: "请输入商品名称", trigger: "blur" },
            { min: 2, max: 15, message: "长度在 2 到 15 个字符", trigger: "blur" },
          ],
          Price: [
            { required: true, message: "请输入价格", trigger: "blur" }
          ],
          Unit: [
            { required: true, message: "请输入单位", trigger: "blur" }
          ],
          Content: [
            { required: true, message: "请输入商品描述", trigger: "blur" }
          ],
          Images: [
            { required: true, message: "请选择图片", trigger: "blur" }
          ]
        },
      }
    },
    model: {
      prop: "dialogFormVisible",
      event: "change",
    },
    props: {
      dialogFormVisible: Boolean,
      editData: Object,
    },
    watch: {
      editData: function (newvalue) {
        console.log('newvalue: ', newvalue);
        this.form = JSON.parse(JSON.stringify(newvalue));
      },
    },
    methods: {
      //上传成功
      handleAvatarSuccess(res) {
        if (res.code == 1) {
          this.$message.success('图片上传成功!');
          this.form.Images = res.data;
        } else {
          this.$message.error(res.msg);
        }
      },
      //上传之前
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isPNG = file.type === 'image/png';
  
        const isLtMB = file.size / 1024 / 1024 < 10;
  
        if (!isJPG && !isPNG) {
          this.$message.error('上传头像图片只能是 JPG 和 PNG 格式!');
        }
        if (!isLtMB) {
          this.$message.error('上传头像图片大小不能超过 10MB!');
        }
        return (isJPG || isPNG) && isLtMB;
      },
  
      //属性切换联动
      propchange() {
        let bol = false;
        this.form.GoodPropertyKey.forEach(v => {
          if (v.checked) {
            bol = true;
          }
        })
        this.form.Use_Property = bol;
      },
  
      //提交按钮
      submitForm(formName) {
        //进行表单验证
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let data = JSON.parse(JSON.stringify(this.form));
            //对数据进行处理  处理属性规格是否勾选保存
            if (!data.Use_Property) {
              data.GoodPropertyKey = [];
            } else {
              data.GoodPropertyKey.forEach((v) => {
                if (!v.checked) {
                  data.GoodPropertyKey = data.GoodPropertyKey.filter(v => v.checked);
                }
              });
            }
            if (data.GoodPropertyKey.length < 1) {
              data.Use_Property = false;
              this.form.Use_Property = false;
            }
  
            // //调用Api 保存数据
            this.axios({
              method: "put",
              url: "goods",
              data: data
            })
              .then((res) => {
                if (res.data.code > 0) {
                  //axios  完成添加
                  this.$message({
                    message: res.data.msg,
                    type: "success",
                    showClose: true,
                    duration: 3000,
                  });
                  //刷新主页面数据
                  this.$emit("refresh");
                  //关闭弹窗
                  this.$emit("change", false);
                } else {
                  this.$message({
                    message: res.data.msg,
                    type: "error",
                    showClose: true,
                    duration: 3000,
                  });
                }
              })
  
          }
          else {
            console.log("error submit!!");
            return false;
          }
        });
      },
    },
    created() {
      this.baseimg = basepath.imgUrl;
      this.baseapi = basepath.apiUrl;
  
      this.axios({
        method: 'get',
        url: 'Spec'
      }).then(response => {
        this.specs = response.data.data;
      });
  
      this.axios({
        method: 'get',
        url: 'GoodsType'
      }).then(response => {
        this.types = response.data.data;
      })
  
      this.form = JSON.parse(JSON.stringify(this.editData));
      console.log('this.editData: ', this.editData);
  
    },
  }
  </script>
  
  <style scoped>

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  </style>